package com.walker.kuyun.ui.activity

import android.animation.ObjectAnimator
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.bumptech.glide.load.resource.bitmap.DrawableTransformation
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition

import com.walker.kuyun.R
import com.walker.kuyun.bean.FavoriteTMBean
import com.walker.kuyun.config.Api
import com.walker.kuyun.config.Const
import com.walker.kuyun.database.getAppDataBase
import com.walker.kuyun.databinding.ActivityTmDetailBinding
import com.walker.kuyun.util.BlurUtils.blur
import com.walker.kuyun.util.Util.getStatusBarHeight
import com.walker.kuyun.util.Util.setTransparentStatusBar
import com.walker.kuyun.util.Util.showToast
import com.walker.kuyun.ui.adapter.TMDetailAdapter
import com.walker.kuyun.ui.fragment.ShareDialogFragment
import com.walker.kuyun.util.visible
import com.walker.kuyun.viewmodel.TMDetailViewModel
import kotlinx.coroutines.*
import java.lang.Exception


class TMDetailActivity : BaseActivity<ActivityTmDetailBinding>(),
    CoroutineScope by CoroutineScope(Dispatchers.IO) {
    private var partUrl: String = ""
    private var isFavorite: Boolean = false
    private lateinit var viewModel: TMDetailViewModel
    private lateinit var adapter: TMDetailAdapter

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setTransparentStatusBar(window, isDark = true)

        val statusBarParams = mBinding.detailStatusBar.layoutParams // 取控件当前的布局参数
        statusBarParams.height = getStatusBarHeight()
        mBinding.detailStatusBar.layoutParams = statusBarParams

        viewModel = ViewModelProvider(this).get(TMDetailViewModel::class.java)
        adapter = TMDetailAdapter(this, viewModel.TMDetailList)

        partUrl = intent.getStringExtra("partUrl") ?: ""

        mBinding.detailToolbar.run {
            layoutToolbar1.setBackgroundColor(Color.TRANSPARENT)
            tvToolbar1Title.isFocused = true
            ivToolbar1Back.setOnClickListener { finish() }
            // 分享
            ivToolbar1Button1.visible()
            ivToolbar1Button1.setOnClickListener {
                ShareDialogFragment().setShareContent(Api.MAIN_URL + partUrl)
                    .show(supportFragmentManager, "share_dialog")
            }
            // 收藏
            launch {
                val favoriteAnime = getAppDataBase().favoriteAnimeDao().getFavoriteAnime(partUrl)
                runOnUiThread {
                    isFavorite = if (favoriteAnime == null) {
                        ivToolbar1Button2.setImageResource(R.drawable.ic_star_border_white_24)
                        false
                    } else {
                        ivToolbar1Button2.setImageResource(R.drawable.ic_star_white_24)
                        true
                    }
                    ivToolbar1Button2.visible()
                }
            }
            ivToolbar1Button2.isEnabled = false
            ivToolbar1Button2.setOnClickListener {
                launch {
                    if (isFavorite) {
                        getAppDataBase().favoriteAnimeDao().deleteFavoriteAnime(partUrl)
                        withContext(Dispatchers.Main) {
                            isFavorite = false
                            ivToolbar1Button2.setImageResource(R.drawable.ic_star_border_white_24)
                            getString(R.string.remove_favorite_succeed).showToast()
                        }
                    } else {
                        getAppDataBase().favoriteAnimeDao().insertFavoriteAnime(
                            FavoriteTMBean(
                                Const.ViewHolderTypeString.ITEM_COVER_8, "",
                                partUrl,
                                viewModel.title,
                                System.currentTimeMillis(),
                                viewModel.cover
                            )
                        )
                        withContext(Dispatchers.Main) {
                            isFavorite = true
                            ivToolbar1Button2.setImageResource(R.drawable.ic_star_white_24)
                            getString(R.string.favorite_succeed).showToast()
                        }
                    }
                }
            }
        }

        mBinding.run {
            detailInfoLayout.layoutManager = LinearLayoutManager(this@TMDetailActivity)
            detailInfoLayout.adapter = adapter

            detailRefreshLayout.setOnRefreshListener { viewModel.getAnimeDetailData(partUrl) }
            detailRefreshLayout.setColorSchemeResources(R.color.main_color)
        }

        viewModel.mldVideoDetailList.observe(this, Observer {
            mBinding.detailRefreshLayout.isRefreshing = false
            if (!it) return@Observer
            mBinding.detailToolbar.ivToolbar1Button2.isEnabled = true

            //先隐藏
            ObjectAnimator.ofFloat(mBinding.ivAnimeDetailActivityBackground, "alpha", 1f, 0f)
                .setDuration(250).start()
            if (viewModel.cover.url.isBlank()) return@Observer
            Glide.with(this)
                .asBitmap()
                .load(viewModel.cover.url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .transition(BitmapTransitionOptions.withCrossFade(350))
                .into(object :
                    CustomViewTarget<ImageView, Bitmap>(mBinding.ivAnimeDetailActivityBackground) {
                    override fun onLoadFailed(errorDrawable: Drawable?) {
                    }

                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        val bitmapDrawable = BitmapDrawable(null, blur(resource))
                        if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
                            bitmapDrawable.colorFilter = PorterDuffColorFilter(
                                Color.DKGRAY, PorterDuff.Mode.MULTIPLY
                            )
                        } else {
                            bitmapDrawable.colorFilter = PorterDuffColorFilter(
                                Color.LTGRAY, PorterDuff.Mode.MULTIPLY
                            )
                        }
                        mBinding.ivAnimeDetailActivityBackground.setImageDrawable(bitmapDrawable)

                        //加载完背景图再显示
                        ObjectAnimator.ofFloat(
                            mBinding.ivAnimeDetailActivityBackground,
                            "alpha",
                            0f,
                            1f
                        )
                            .setDuration(250).start()
                    }

                    override fun onResourceCleared(placeholder: Drawable?) {

                    }
                })

            mBinding.detailToolbar.tvToolbar1Title.text = viewModel.title
            adapter.notifyDataSetChanged()
        })

        mBinding.detailRefreshLayout.isRefreshing = true
        viewModel.getAnimeDetailData(partUrl)
    }

    override fun getBinding(): ActivityTmDetailBinding =
        ActivityTmDetailBinding.inflate(layoutInflater)

    fun getPartUrl(): String = partUrl
}
